package com.sxhuayuan.parking.controller.admin;

import com.sxhuayuan.parking.compenent.Message;
import com.sxhuayuan.parking.compenent.Pageable;
import com.sxhuayuan.parking.compenent.web.RespMessage;
import com.sxhuayuan.parking.compenent.web.RespMessage.Status;
import com.sxhuayuan.parking.controller.BaseController;
import com.sxhuayuan.parking.entity.Agent;
import com.sxhuayuan.parking.entity.OemConfig;
import com.sxhuayuan.parking.entity.Salesman;
import com.sxhuayuan.parking.service.AgentService;
import com.sxhuayuan.parking.service.OemConfigService;
import com.sxhuayuan.parking.service.SalesmanService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 *
 */
@RestController("adminAgentController")
@RequestMapping("/admin/agent")
public class AgentController extends BaseController {

	@Resource(name = "agentServiceImpl")
	AgentService agentService;

	@Resource(name = "salesmanServiceImpl")
	SalesmanService salesmanService;
	@Resource(name = "oemConfigServiceImpl")
	OemConfigService oemConfigService;

	@Value("${wechat.rate}")
	private float weixinRate;
	@Value("${alipay.rate}")
	private float alipayRate;

	/**
	 * 删除用户
	 */
	@RequestMapping("/delete")
	public RespMessage deleteAgent(Long id) {
		if (Objects.isNull(id)) {
			return invalidToken();
		}
		agentService.delete(id);
		return RespMessage.success();

	}

	/**
	 * 查询所有代理
	 */
	@RequestMapping("/list")
	public RespMessage pagelist(@RequestBody Pageable pageable) {
		Agent agent = null;
		return RespMessage.builder().success().setDatas(agentService.findPage(pageable, agent)).build();
	}

	/**
	 * 根据用户名查询
	 */
	@RequestMapping("/get/username")
	public RespMessage findByUserNameAndPassWord(String userName) {
		if (!StringUtils.isNotBlank(userName)) {
			return invalidToken();
		}
		Agent agent = agentService.findByUsername(userName);
		return RespMessage.builder().success().setDatas(agent).build();
	}

	/**
	 * 添加代理
	 */
	@RequestMapping("/save")
	public RespMessage save(@Validated @RequestBody Agent agent, HttpServletRequest request) {
		if (agentService.usernameExists(agent.getUsername())) {
			return RespMessage.builder().validError().setErr(Message.FORM_UNIQUE_INVALID, "用户名").build();
		}

		if (agent.getParent() != null) {
			if (agent.getWeixinRate() < agent.getParent().getWeixinRate()) {
				return RespMessage.error("微信费率不能小于上级代理费率");
			}

			if (agent.getAlipayRate() < agent.getParent().getAlipayRate()) {
				return RespMessage.error("支付宝费率不能小于上级代理费率");
			}
			agent.setSalesmanId(null);
			Agent parent = agent.getParent();
			if (parent.getOemConfig() == null) {
				return RespMessage.error("父代理的oem未配置");
			} else {
				agent.setOemConfig(parent.getOemConfig());
			}
		} else {
			if (agent.getSalesmanId() == null) {
				return RespMessage.error("一级代理需要选择业务员");
			}
			if (salesmanService.findOne(agent.getSalesmanId()) == null) {
				return RespMessage.error("业务员不存在");
			}
			if (agent.getWeixinRate() < weixinRate) {
				return RespMessage.error("微信费率不能小于官方费率");
			}
			if (agent.getAlipayRate() < alipayRate) {
				return RespMessage.error("支付宝费率不能小于官方费率");
			}
			OemConfig oem = agent.getOemConfig();
			if (oem == null || oem.getId() == null) {
				return RespMessage.error("请选择一个oem配置");
			} else {
				OemConfig one = oemConfigService.findOne(oem.getId());
				if (one == null) {
					return RespMessage.error("oem配置不存在");
				} else {
					agent.setOemConfig(oem);
				}
			}
		}
		agentService.save(agent, agent.getParent());
		return RespMessage.success();
	}

	/**
	 * 锁定 启用
	 */
	@RequestMapping("/locked/or/enabled")
	public RespMessage enable(Long id, String type, Boolean value) {
		if (Objects.isNull(id) || Objects.isNull(value) || Objects.isNull(type)) {
			return RespMessage.error(Status.VALID_ERR, Message.FORM_VALID_FAIL);
		}
		Agent agent = agentService.findOne(id);

		if ("Locked".equals(type)) {
			agent.setIsLocked(value);
			agentService.update(agent);
			return RespMessage.success();
		} else if ("Enabled".equals(type)) {
			agent.setIsEnabled(value);
			agentService.update(agent);
			return RespMessage.success();
		} else {
			return RespMessage.error("type错误");
		}

	}

	@RequestMapping(value = "/get", method = RequestMethod.GET)
	public RespMessage get(Long id) {
		Agent agent = agentService.findOne(id);
		return RespMessage.builder().success().setDatas(agent).build();
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public RespMessage update(@Validated @RequestBody Agent agent, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return RespMessage.error(Status.VALID_ERR, Message.FORM_VALID_FAIL);
		}
		if (agent.getParent() != null) {
			if (agent.getWeixinRate() < agent.getParent().getWeixinRate()) {
				return RespMessage.error("微信费率不能小于上级代理费率");
			}

			if (agent.getAlipayRate() < agent.getParent().getAlipayRate()) {
				return RespMessage.error("支付宝费率不能小于上级代理费率");
			}
		} else {
			if (agent.getWeixinRate() < weixinRate) {
				return RespMessage.error("微信费率不能小于官方费率");
			}

			if (agent.getAlipayRate() < alipayRate) {
				return RespMessage.error("支付宝费率不能小于官方费率");
			}
		}
		if (agent.getOemConfig()!=null){
			OemConfig one = oemConfigService.findOne(agent.getOemConfig().getId());
			if (one == null) {
				return RespMessage.error("oem配置未找到");
			}
			agent.setOemConfig(one);
		}
		if (agent.getSalesmanId()!=null){
			Salesman one = salesmanService.findOne(agent.getSalesmanId());
			if (one == null) {
				return RespMessage.error("业务员未找到");
			}
			agent.setSalesmanId(one.getId());
		}
		if (agent.getId() != null) {
			agentService.update(agent);
			return RespMessage.success();
		}
		return RespMessage.error("更新失败");
	}

	/**
	 * 管理员查询全部代理
	 */
	@GetMapping(value = "/getall")
	public RespMessage getAll() {
		List<Agent> all = agentService.findAll();
		return RespMessage.builder().success().setDatas(all).build();
	}
}
